package com.self.war.bootstrap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import com.myself.entities.Post;
import com.myself.repositories.PostRepository;

/**
 * Servlet implementation class BootstrapServlets
 */
@Component("bootstrapServlet")
public class BootstrapServlet implements HttpRequestHandler {
	private static Logger LOGGER = LoggerFactory
			.getLogger(BootstrapServlet.class);

	@Autowired
	private PostRepository postRepository;

	@PostConstruct
	public void initData() {
		LOGGER.debug("performing bootstrap phase :insert data.....");
		List<Post> posts = new ArrayList<Post>();
		for (int i = 0; i < 1000; i++) {
			Post post = new Post();
			post.setPostDate(new Date());
			post.setTitle("title" + i);
			posts.add(post);
		}
		postRepository.save(posts);
		LOGGER.debug(" bootstrap phase finished.....");

	}

	/**
	 * @return the postRepository
	 */
	public PostRepository getPostRepository() {
		return postRepository;
	}

	/**
	 * @param postRepository
	 *            the postRepository to set
	 */
	public void setPostRepository(PostRepository postRepository) {
		this.postRepository = postRepository;
		initData();

	}

	@Override
	public void handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		throw new ServletException("DO NOT USE THIS URL");
	}

}
